﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：庄金冬 
    //
    // 文件名：BLL_User.cs
    // 文件功能描述：用户操作业务逻辑类,实现接口IBLL_User,继承自类MarshalByRefObject
    // 创建标识：庄金冬2009-03-06
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
    // 审核时间：
    // 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Text;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.DAL;
using System.Data;

namespace HZ.DrugTrade.BLL
{
    [Serializable]
    /// <summary>
    /// 用户操作业务逻辑类,实现接口IBLL_User,继承自类MarshalByRefObject
    /// </summary>
    public class BLL_User : MarshalByRefObject, IBLL_User
    {
        #region IBLL_User 成员
        BLL_Log log = new BLL_Log();
        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns>用户集合</returns>
        ///  HZ.DrugTrade.BLL.BLL_Log log = new BLL.BLL_Log();
        public IList<User> GetAllUser(int currentPage, int pageSize, out int totalRecord)
        {
            BLL_UserSession.CheckSession();

            HZ.DrugTrade.Model.Query.User QueryUser = new HZ.DrugTrade.Model.Query.User();
            return GetUserByWhere(QueryUser, currentPage, pageSize, out  totalRecord);
        }

        /// <summary>
        /// 按角色获取所有主用户
        /// </summary>
        /// <param name="role">角色（Role仅RoleID须赋值）</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns>主用户集合（不含权限角色等相关信息）</returns>
        public IList<User> GetAllUserByRole(Role role, int currentPage, int pageSize, out int totalRecord)
        {
            BLL_UserSession.CheckSession();
            HZ.DrugTrade.Model.Query.User QueryUser = new HZ.DrugTrade.Model.Query.User();
            QueryUser.RoleID = role.RoleID;
            QueryUser.IsAdmin = true;
            return GetUserByWhere(QueryUser, currentPage, pageSize, out  totalRecord);
        }

        /// <summary>
        /// 根据编号获取用户（不含权限信息，角色信息，权限信息，机构信息）
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <returns></returns>
        public User GetUserByUserID(string userid)
        {
            BLL_UserSession.CheckSession();
            return DAL_User.GetUserByUserID(userid);
        }

        /// <summary>
        /// 根据编号获取用户（包含用户信息，角色信息，权限信息，机构信息）
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <returns></returns>
        public User GetUserInfoByUserID(string userid)
        {
            BLL_UserSession.CheckSession();
            return DAL_User.GetUserInfoByUserID(userid);
        }

        /// <summary>
        ///  获取某个主用户的子用户
        /// </summary>
        /// <param name="userid">主用户编号</param>
        /// <returns>用户集合</returns>
        public IList<User> GetChildUserByUserID(string userid)
        {
            BLL_UserSession.CheckSession();

            return DAL_User_Role.GetChildUserByUserID(userid);
        }

        /// <summary>
        /// 更新用户信息[名称、是否启用](0,更新失败;1,更新成功;2,用户编号不存在;)
        /// </summary>
        /// <param name="user">用户[名称、是否启用]</param>
        /// <returns>(0,更新失败;1,更新成功;2,用户编号不存在;)</returns>
        public int UpdateUser(User user)
        {
            BLL_UserSession.CheckSession();

            if (!string.IsNullOrEmpty(user.UserPassword))
            {
                user.UserPassword = HZ.Fun2.GetMd5(user.UserPassword);

            }
            int state = DAL_User.UpdateUser(user, 0);
            if(state==1){
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format( "{0}用户更新信息", user.UserID)}); 
            }
            return state;
        }

        /// <summary>
        /// 获取用户的操作权限
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <returns>操作权限集合</returns>
        public IList<OperatingRule> GetUserOperatingRule(string userid)
        {
            return DAL_User.GetUserOperatingRule(userid);
        }

        /// <summary>
        /// 修改密码(0,更新失败;1,更新成功;2,原密码错误)
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <param name="oldpassword">原始密码</param>
        /// <param name="newpassword">新密码</param>
        /// <returns>(0,更新失败;1,更新成功;2,原密码错误)</returns>
        public int UpdatePassword(string userid, string oldpassword, string newpassword)
        {
            oldpassword = HZ.Fun2.GetMd5(oldpassword);
            newpassword = HZ.Fun2.GetMd5(newpassword);
            BLL_UserSession.CheckSession();
            int result = DAL_User.UpdatePassword(userid, oldpassword, newpassword, 1);
            if (result == 1) { BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = "修改密码成功",ClientIP=HZ.Fun.GetClientIP() }); }
            return result;
        }

        /// <summary>
        /// 密码初始化
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <param name="newpassword">初始化密码</param>
        /// <returns></returns>
        public bool InitPassword(string userid, string newpassword)
        {
            BLL_UserSession.CheckSession();
            newpassword = HZ.Fun2.GetMd5(newpassword);
            bool result = DAL_User.UpdatePassword(userid, "", newpassword, 0) == 1;
            if(result){
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("{0}用户初始化密码", userid) }); 
            }
            return result;
        }

        /// <summary>
        /// 密码初始化
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <param name="newpassword">初始化密码</param>
        /// <returns></returns>
        public bool InitPassword(IList<User> lst)
        {
            BLL_UserSession.CheckSession();
            var h = HZ.Data.DbHelperFactory.Create();
            try
            {
                h.BeginTrans();
                string strSql = string.Empty;
                foreach (User item in lst)
                {

                    strSql = string.Format(@"UPDATE TB_user  SET UserPassword = '{0}',IsUsing=1 WHERE UserID = '{1}' ", HZ.Fun2.GetMd5(item.UserPassword), item.UserID);

                    h.ExecuteNonQuery(strSql);
                }

                h.CommitTrans();
                return true;
            }
            catch (Exception ee)
            {
                h.RollTrans();
                HZ.Common.log4netManager.LogDebug("InitPassword(IList<User> lst)", ee.Message, ee);
                return false;
            }
        }
        /// <summary>
        /// 密码初始化
        /// </summary>
        /// <param name="userids">用户编号集合</param>
        /// <param name="newpassword">初始化密码</param>
        /// <returns></returns>
        public bool InitPassword(List<string> userids, string newpassword)
        {
            if (userids != null && userids.Count==0)
            {
                return true;
            }
            newpassword = HZ.Fun2.GetMd5(newpassword);
            BLL_UserSession.CheckSession();
            //处理用户编号
            StringBuilder sbUserIDs = new StringBuilder("");
            string strUserIDs = "";
            if (userids != null)
            {
                if (userids.Count > 0)
                {
                    foreach (string UserID in userids)
                    {
                        sbUserIDs.Append(UserID + ",");
                    }
                    strUserIDs = sbUserIDs.ToString().Trim().Substring(0, sbUserIDs.Length - 1);
                }
            }
            log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("将用户{0},密码初始化", sbUserIDs) });
            return DAL_User.ResetUserPassword(strUserIDs, newpassword) == 1;
        }
       

        /// <summary>
        /// 用户锁定
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <returns></returns>
        public bool LockUser(string userid)
        {
            BLL_UserSession.CheckSession();
            bool result = DAL_User.LockUser(userid);
            if (result)
            {
                log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("{0}用户锁定", userid) });

            }
            return result;

        }


        /// <summary>
        /// 用户解锁
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <returns></returns>
        public bool UnblockUser(string userid)
        {
            BLL_UserSession.CheckSession();
          
            bool result = DAL_User.UnblockUser(userid);

            if (result){
                log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("{0}用户解锁", userid) });
            }
            return result;
          
        }


        /// <summary>
        /// 用户锁定（批量）
        /// </summary>
        /// <param name="userids">用户编号集合</param>
        /// <returns></returns>
        public bool LockUser(List<string> userids)
        {
            BLL_UserSession.CheckSession();
            //处理用户编号
            StringBuilder sbUserIDs = new StringBuilder("");
            string strUserIDs = "";
            if (userids != null && userids.Count > 0)
            {
                if (userids.Count > 0)
                {
                    foreach (string UserID in userids)
                    {
                        sbUserIDs.Append(UserID + ",");
                    }

                    strUserIDs = sbUserIDs.ToString().Trim().Substring(0, sbUserIDs.Length - 1);

                }
                log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("{0}用户锁定", strUserIDs) });
                return DAL_User.LockOrUnblockUser(strUserIDs, 0) == 1;
            }
            else
            {
                return true;
            }


           
        }

        /// <summary>
        /// 用户解锁（批量）
        /// </summary>
        /// <param name="userids">用户编号集合</param>
        /// <returns></returns>
        public bool UnblockUser(List<string> userids)
        {
            BLL_UserSession.CheckSession();

            //处理用户编号
            StringBuilder sbUserIDs = new StringBuilder("");
            string strUserIDs = "";
            if (userids != null)
            {
                if (userids.Count > 0)
                {
                    foreach (string UserID in userids)
                    {
                        sbUserIDs.Append(UserID + ",");
                    }

                    strUserIDs = sbUserIDs.ToString().Trim().Substring(0, sbUserIDs.Length - 1);

                }
            }

            log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("{0}用户解锁", strUserIDs) });
            return DAL_User.LockOrUnblockUser(strUserIDs, 1) == 1;
        }

        /// <summary>
        /// 删除用户(0,删除失败;1,删除成功;2,该用户不存在;)
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <returns>(0,删除失败;1,删除成功;2,该用户不存在;)</returns>
        public int DeleteUser(string userid)
        {
            BLL_UserSession.CheckSession();
            int state = DAL_User.DeleteUser(userid);
            if (state == 1)
            {
                log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("{0}用户被删除", userid) });
            }
            return state;    
        }

        /// <summary>
        /// 添加用户同时设置权限(0,添加失败;1,添加成功;2,用户编号已存在;)
        /// </summary>
        /// <param name="user">用户对象（每个用户的UserRole仅RoleID须赋值，Org仅OrgID须赋值）</param>
        /// <param name="ruleIList">操作权限集合（每个权限仅RuleID须赋值）</param>
        /// <returns>(0,添加失败;1,添加成功;2,用户编号已存在;)</returns>
        public int AddUser_OperatingRule(User user, IList<OperatingRule> ruleIList)
        {
            BLL_UserSession.CheckSession();
            if (!string.IsNullOrEmpty(user.UserPassword))
            {
                user.UserPassword = HZ.Fun2.GetMd5(user.UserPassword);

            }

             int result =DAL_User.AddUser_OperatingRule(user, ruleIList);

            if (result==1){
                log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("添加用户", user.UserName) });
            }
             return result;
        }

        /// <summary>
        /// 设置用户的操作权限
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <param name="ruleIList">操作权限集合</param>
        /// <returns></returns>
        public bool SetUserOperatingRule(string userid, IList<OperatingRule> ruleIList)
        {
            BLL_UserSession.CheckSession();
            return DAL_User.SetUserOperatingRule(userid, ruleIList);
        }


        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="user">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<User> GetUserByWhere(HZ.DrugTrade.Model.Query.User user, int currentPage, int pageSize, out int totalRecord)
        {
            BLL_UserSession.CheckSession();
            return DAL_User.GetUserByWhere(user, currentPage, pageSize, out totalRecord);
        }


        /// <summary>
        /// 更新用户信息[名称、是否启用]同时设置权限(0,更新失败;1,更新成功;2,用户编号不存在;)
        /// </summary>
        /// <param name="user">用户[名称、是否启用、权限集合]</param>
        /// <returns>(0,更新失败;1,更新成功;2,用户编号不存在;)</returns>
        public int UpdateUserRule(User user)
        {
            BLL_UserSession.CheckSession();
            return DAL_User.UpdateUserRule(user);
        }

        /// <summary>
        /// 授权(0,失败;1,成功;)
        /// </summary>
        /// <param name="Orgs">机构字典(key:OrgID,value:RoleID)</param>
        /// <returns>(0,失败;1,成功;)</returns>
        public int AuthorizeOrg(IDictionary<string, string> Orgs)
        {
            BLL_UserSession.CheckSession();
             int result  =DAL_User.AuthorizeOrg(Orgs, 1);
            if(result==1){
             log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("{0}授权", Orgs) });
            }
            return result;
        }

        /// <summary>
        /// 撤权(0,失败;1,成功;)
        /// </summary>
        /// <param name="Orgs">机构字典(key:OrgID,value:RoleID)</param>
        /// <returns>(0,失败;1,成功;)</returns>
        public int RevokeOrg(IDictionary<string, string> Orgs)
        {
            BLL_UserSession.CheckSession();
              int  result = DAL_User.AuthorizeOrg(Orgs, 0);
            if (result == 1)
            {
                log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("{0}撤权", Orgs) });
            }
            return result;
        }

        /// <summary>
        /// 条件机构用户查询（含机构角色相关信息）
        /// </summary>
        /// <param name="user">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<HZ.DrugTrade.Model.View.OrgUsers> GetOrgUsersByWhere(HZ.DrugTrade.Model.Query.OrgUsers user, int currentPage, int pageSize, out int totalRecord)
        {
            BLL_UserSession.CheckSession();
            return DAL_User.GetOrgUsersByWhere(user, currentPage, pageSize, out totalRecord);
        }

        /// <summary>
        /// 条件机构用户查询（含机构角色相关信息）
        /// </summary>
        /// <param name="user">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<HZ.DrugTrade.Model.View.HospitalUsers> GetHospitalUsersByWhere(HZ.DrugTrade.Model.Query.HospitalUsers user, int currentPage, int pageSize, out int totalRecord)
        {
            BLL_UserSession.CheckSession();
            return DAL_User.GetHospitalUsersByWhere(user, currentPage, pageSize, out totalRecord);
        }

        /// <summary>
        /// 条件医疗机构入围授权查询
        /// </summary>
        /// <param name="user">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<HZ.DrugTrade.Model.View.HospitalCatalogManageRule> GetHospitalCatalogManageRulesByWhere(HZ.DrugTrade.Model.Query.HospitalCatalogManageRule user, int currentPage, int pageSize, out int totalRecord)
        {
            BLL_UserSession.CheckSession();
            return DAL_User.GetHospitalCatalogManageRulesByWhere(user, currentPage, pageSize, out totalRecord);
        }

        /// <summary>
        /// 授权医疗机构入围(0,失败;1,成功;)
        /// </summary>
        /// <param name="userIDs">主用户编号集合（如：1,2,3）</param>
        /// <param name="operatingRuleID">操作编号</param>
        /// <returns>(0,失败;1,成功;)</returns>
        public int AuthorizeHospitalCatalogManageRule(string userIDs, string operatingRuleID)
        {
            BLL_UserSession.CheckSession();
            int result = DAL_User.AuthorizeHospitalCatalogManageRule(userIDs, 1, operatingRuleID);
            if (result == 1) {
                log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("{0}授权医疗机构入围(", userIDs) });
            }
            return result;
        }


        /// <summary>
        /// 撤权医疗机构入围(0,失败;1,成功;)
        /// </summary>
        /// <param name="userIDs">主用户编号集合（如：1,2,3）</param>
        /// <param name="operatingRuleID">操作编号</param> 
        /// <returns>(0,失败;1,成功;)</returns>
        public int RevokeHospitalCatalogManageRule(string userIDs, string operatingRuleID)
        {
            BLL_UserSession.CheckSession();
            int result =  DAL_User.AuthorizeHospitalCatalogManageRule(userIDs, 0, operatingRuleID);
            if (result == 1)
            {
                log.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("{0}撤权医疗机构入围(", userIDs) });
            }
            return result;

        }

        public User GetAdminUserByID(string userid)
        {
            BLL_UserSession.CheckSession();
            string adminuserid = DAL.DAL_User.GetAdminUserID(userid);
            return GetUserInfoByUserID(adminuserid);
        }


        #endregion
    }
}
